//
//  AppDelegate.swift
//  home
//
//  Created by Yun Zeng on 2019/8/4.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit
import CoreLocation

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var account = Account.instance
    var locationManager: CLLocationManager?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        self.registerForPushNotification()
        self.locationManager = CLLocationManager()
        self.locationManager?.allowsBackgroundLocationUpdates = true
        self.locationManager?.delegate = self
        return true
    }

    // MARK: UISceneSession Lifecycle
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        let aps = userInfo["aps"] as! [String: AnyObject]
        if let jsondData = try? JSONSerialization.data(withJSONObject: aps, options: .sortedKeys) {
            let jsonString = String(data: jsondData, encoding: .utf8)!
            Logger.Info("apns: " + jsonString)
        }
    
        completionHandler(.newData)
        let notification = Notification(name: NSNotification.Name(rawValue: "APNSNotification"), object: nil, userInfo: aps)
        NotificationCenter.default.post(notification)
    }
    
}

// 推送消息通知
extension AppDelegate: UNUserNotificationCenterDelegate {
    func registerForPushNotification() {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { (granted, err) in
            Logger.Info("current setting \(granted)")
        }
        
        let generalCateGory = UNNotificationCategory(
            identifier: "GENERAL",
            actions: [],
            intentIdentifiers: [],
            options: .customDismissAction
        )
        center.setNotificationCategories([generalCateGory])
        UIApplication.shared.registerForRemoteNotifications()
        UNUserNotificationCenter.current().delegate = self
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let tokenPart = deviceToken.map { (data) -> String in
            return String(format: "%02.2hhx", data)
        }
        let token = tokenPart.joined()
        Logger.Info("token: \(token)")
        self.account.apnsToken = token
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        Logger.Error("mark err: \(error)")
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        if let aps = userInfo["aps"] as? [String: AnyObject] {
            if let jsondData = try? JSONSerialization.data(withJSONObject: aps, options: .sortedKeys) {
                let jsonString = String(data: jsondData, encoding: .utf8)!
                Logger.Info("notification: " + jsonString)
            }
        }
        completionHandler()
    }
    
}

// 地理围栏通知部分
extension AppDelegate: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
        if region is CLCircularRegion {
            LocationManager.postMemberState(membership: Account.instance.membership, home: HomeManager.instance.current!.id, state: .arrive)
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
        if region is CLCircularRegion {
            LocationManager.postMemberState(membership: Account.instance.membership, home: HomeManager.instance.current!.id, state: .leave)
        }
    }
}









